from flask import Flask, render_template, request, redirect, url_for, session, jsonify
import os
from datetime import datetime

app = Flask(__name__)
app.secret_key = os.urandom(24)  # 用于会话管理

# 模拟用户数据库
users = {
    'admin': 'password123',
    'user1': '123456'
}

# 模拟剪辑记录数据
edit_records = []

@app.route('/')
def home():
    """主界面路由 - 显示视频剪辑功能"""
    return render_template('index.html')

@app.route('/profile')
def profile():
    """我的页面路由 - 显示用户信息、登录状态等"""
    return render_template('profile.html')

@app.route('/api/login', methods=['POST'])
def api_login():
    """API登录处理路由 - 仅处理POST请求"""
    username = request.form.get('username')
    password = request.form.get('password')
    
    # 验证用户名和密码
    if username in users and users[username] == password:
        session['username'] = username
        session['logged_in'] = True
        return jsonify({'success': True, 'message': '登录成功'})
    else:
        return jsonify({'success': False, 'message': '用户名或密码错误'})

@app.route('/logout')
def logout():
    """登出处理路由"""
    session.clear()
    return jsonify({'success': True, 'message': '已退出登录'})

@app.route('/api/user-status')
def user_status():
    """获取用户登录状态API"""
    if 'logged_in' in session and session['logged_in']:
        return jsonify({
            'logged_in': True,
            'username': session.get('username', '')
        })
    else:
        return jsonify({'logged_in': False})

@app.route('/api/edit-records')
def get_edit_records():
    """获取用户剪辑记录API"""
    if 'logged_in' not in session or not session['logged_in']:
        return jsonify({'error': '请先登录'}), 401
    
    user_records = [record for record in edit_records if record['username'] == session['username']]
    return jsonify(user_records)

@app.route('/api/save-edit', methods=['POST'])
def save_edit():
    """保存剪辑记录API"""
    if 'logged_in' not in session or not session['logged_in']:
        return jsonify({'error': '请先登录'}), 401
    
    data = request.get_json()
    record = {
        'id': len(edit_records) + 1,
        'username': session['username'],
        'title': data.get('title', '未命名作品'),
        'template': data.get('template', ''),
        'intro': data.get('intro', ''),
        'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    }
    edit_records.append(record)
    return jsonify({'success': True, 'message': '保存成功'})

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
